; Exercise 1.6

;; Support functions:

(define (improve guess x)
  (average guess (/ x guess)))

(define (average x y)
  (/ (+ x y) 2))

(define (square x)
  (* x x))

(define (good-enough? guess x)
  (< (abs (- (square guess) x)) 0.001))

(define (sqrt x)
  (sqrt-iter 1.0 x))

; Now the exercise begins:
; Given the following if implementation:

(define (new-if predicate then-clause else-clause)
  (cond (predicate then-clause)
        (else else-clause)))

; And the following implementation of the square-root program:

(define (sqrt-iter guess x)
  (new-if (good-enough? guess x)
          guess
          (sqrt-iter (improve guess x)
                     x)))

; Describe what happens when one attemps to use this to compute square roots.

; By evaluating the square root function, one realizes that it enters an
; infinite loop. The more appropriate conjecture for the reason of that is
; that the new-if is always evaluating the else-clause. Why? Well, let's
; illustrate the call to (sqrt 1.0):
;
; (sqrt 1.0)
;      |
;      V
; (sqrt-iter 1.0 1.0)
;      |
;      V
; (new-if (good-enough? 1.0 1.0)
;         1.0
;         (sqrt-iter (improve 1.0 1.0)
;                    1.0))
;
; What happens here is that the interpreter uses the applicative order and, in
; one part of the execution it would try to, again, evaluate sqrt-iter,
; causing an infinite loop.
;
; The best example I was able to come up with that shows this problem is the
; following:
; 
; 1. (if (= n 1) 1 (blah))
; 2. (new-if (= n 1) 1 (blah))
;
; In 1., the interpreter would see that the evaluation is true and would issue
; the correct answer, one.
;
; In 2., in contrast, the interpreter would try to evaluate (blah) before
; evaluating new-if, resulting in an error because of an unbound variable.
;


; vim: set lisp expandtabs smarttabs

